#include "AIEngine.h"

AIEngine::AIEngine()
{
	board = new Board();
	playerTable[p1] = new Player( p1 );
	playerTable[p2] = new Player( p2 );
	movesList.clear();
    regularMovesListTemp.clear();
    currentPlayer = p1;
    isFinished = false;
    movesJouables.clear();
}


AIEngine::~AIEngine()
{
	delete board;
	delete playerTable[p1];
	delete playerTable[p2];
}


//Fction de connection des modules
void AIEngine::connecting( GameEngine* ge )
{
	connect( ge, SIGNAL( askingAIMove(GameEngine*) ), this, SLOT( chooseMove(GameEngine*) ) );
	connect( this, SIGNAL( sendingMove(int,int) ), ge, SLOT( recupMove(int,int) ) );
}
		

//Selectionne le move à jouer (traitement global)
void AIEngine::chooseMove( GameEngine* ge )
{
//	cout << "Entre ds AIEngine::chooseMove()" << endl;
	initialization(ge);
	Move m = randomMove();
//	cout << "Emission de sendingMove()" << endl;
	emit sendingMove( m.getX(), m.getY() );
}


//Fonction qui initialise le moteur d'IA
void AIEngine::initialization(GameEngine* ge)
{
//	cout << "Entre ds AIEngine::initialization()" << endl;
	*board = *( ge->getBoard() );
	*playerTable[p1] = *( ge->getPlayer(p1) );
	*playerTable[p2] = *( ge->getPlayer(p2) );
	movesList = ge->getMovesList();
	regularMovesListTemp = ge->getRegularMovesListTemp();
	movesJouables.clear();
	currentPlayer = ge->getCurrentPlayer();
}

	
//Choisit aléatoirement un coup à jouer
Move AIEngine::randomMove()
{
//	cout << "Entre ds AIEngine::randomMove()" << endl;
//	cout << "currentPlayer = " << currentPlayer << endl;
	
	if( !regularMovesListTemp.empty() )
	{
//		cout << "Liste regularMovesListTemp" << endl;
	    for( int i=0 ; i<regularMovesListTemp.size() ; i++ )
	    {
//	    	regularMovesListTemp[i].affichage();
	    	if( regularMovesListTemp[i].getColor() == playerTable[currentPlayer]->getColor() )
	    	{
	        	movesJouables.push_back(regularMovesListTemp[i]);	
	    	}
	    }
	    
	    //génération d'un entier aléatoire
	    int num = (int) (0 + ((float) rand() / RAND_MAX * (movesJouables.size()-1 - 0 + 1)));
	    
//	    cout << "\tmovesJouables.size = " << movesJouables.size() << endl;
//	    cout << "\tnum aleatoire = " << num << endl;
	    
//	    cout << "Liste après suppression:" << endl;
//	    for( int i=0 ; i<movesJouables.size() ; i++ )
//	    {
//	    	movesJouables[i].affichage();
//	    }
	    
	    return movesJouables[num];
	}
	else 
	{
		return Move(-1,-1);
	}
}
